Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extend quierier test #210

Merged
merged 17 commits into from
Mar 22, 2024
Merged

Extend quierier test #210

merged 17 commits into from
Mar 22, 2024

Conversation

jbernal87
Copy link
Contributor

@jbernal87 jbernal87 commented Feb 2, 2024

Summary by CodeRabbit

  • New Features
    • Introduced handling for transient spot and derivative orders, including creation and query capabilities.
    • Added new message types and queries for trading activities, market information retrieval, and order cancellation strategies.
    • Enhanced functionality for querying various market parameters, subaccount positions, and oracle data.
  • Bug Fixes
    • Added error handling for unrecognized replies, reply parsing failures, and sub-message failures.
  • Refactor
    • Updated function signatures and code structure for improved clarity and organization.
    • Added new modules for handling specific functionalities such as order management, queries, and replies.
  • Tests
    • Expanded testing modules to cover spot and derivative market functionalities, staking queries, and token factory operations.
  • Documentation
    • Updated existing summary and code comments for better understanding of the changes.

@jbernal87 jbernal87 marked this pull request as draft February 2, 2024 15:14
query exchange param test
query exchange spot market test
query subaccount deposit test
@jbernal87 jbernal87 force-pushed the f/testing-suite-extension branch from ab36941 to cbfd7a7 Compare February 5, 2024 22:27
Copy link

coderabbitai bot commented Feb 22, 2024

Walkthrough

The update enhances the Injective CosmWasm mock environment, focusing on trading functionalities for both spot and derivative markets. It introduces new constants, message types, and error handling mechanisms, alongside restructured code for better organization. Key additions include functions for order management, queries related to trading activities, and tests covering various aspects of market interactions. This comprehensive update aims to improve the simulation of trading activities within the Injective ecosystem.

Changes

Files Summary
contracts/injective-cosmwasm-mock/src/contract.rs, .../lib.rs, .../state.rs Updated summary, added constants, functions, and modules for enhanced trading functionality.
.../error.rs Added error variants for improved error handling.
.../handle.rs, .../order_management.rs Functions for managing spot and derivative orders.
.../query.rs, .../msg.rs Enhanced querying capabilities and new message types for trading.
.../reply.rs Functions to handle replies for order creation.
.../testing/... Expanded testing modules covering spot, derivative markets, and other functionalities.
packages/injective-cosmwasm/... Adjustments in response structures and querier implementations.
packages/injective-protobuf/src/proto/mod.rs Reordered module declarations for better organization.

🐇✨
In the realm of code, where logic weaves,
A rabbit hopped, with updates up its sleeves.
Spot and derivative trades, it did enhance,
With queries, errors, and tests that dance.
Through CosmWasm's fields, it leaps with glee,
"To improve," it chirps, "is to be free!"
🌟🐾


Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit-tests for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit tests for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

@jbernal87 jbernal87 force-pushed the f/testing-suite-extension branch from 49392b2 to cfb63df Compare February 23, 2024 17:46
@jbernal87 jbernal87 marked this pull request as ready for review March 9, 2024 09:14
@jbernal87 jbernal87 requested a review from maxrobot March 9, 2024 09:14
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Status

Actionable comments generated: 23

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between ac48b89 and 50f00df.
Files ignored due to path filters (2)
  • Cargo.lock is excluded by: !**/*.lock
  • contracts/injective-cosmwasm-mock/Cargo.toml is excluded by: !**/*.toml
Files selected for processing (17)
  • .github/workflows/Basic.yml (3 hunks)
  • contracts/injective-cosmwasm-mock/src/contract.rs (2 hunks)
  • contracts/injective-cosmwasm-mock/src/error.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/handle.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/lib.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/msg.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/order_management.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/reply.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/state.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/mod.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/query_exchange_derivative_tests.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/query_exchange_tests.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/types.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/utils.rs (1 hunks)
  • packages/injective-cosmwasm/src/exchange/response.rs (1 hunks)
  • packages/injective-cosmwasm/src/exchange_mock_querier.rs (2 hunks)
  • packages/injective-cosmwasm/src/querier.rs (3 hunks)
Files skipped from review due to trivial changes (1)
  • contracts/injective-cosmwasm-mock/src/testing/mod.rs
Additional comments: 33
contracts/injective-cosmwasm-mock/src/lib.rs (1)
  • 7-11: The addition of new modules handle, order_management, reply, state, and types is correctly implemented. Ensure that these modules are properly integrated and used throughout the contract to enhance its functionality as intended.
contracts/injective-cosmwasm-mock/src/state.rs (1)
  • 5-11: The introduction of ORDER_CALL_CACHE and the CacheOrderInfo struct is correctly implemented. Ensure that interactions with this cache are properly handled, including error scenarios, to maintain the contract's robustness.
contracts/injective-cosmwasm-mock/src/error.rs (1)
  • 8-13: The addition of new error variants UnrecognizedReply, ReplyParseFailure, and SubMsgFailure is correctly implemented. These errors enhance the contract's robustness by providing clear, context-specific error messages for reply handling scenarios.
.github/workflows/Basic.yml (1)
  • 27-27: The update of the Rust toolchain version to 1.73.0 in the GitHub Actions workflow is correctly implemented. Ensure that the project builds successfully and all tests pass with this new toolchain version.

Also applies to: 44-44, 68-68, 76-76, 83-83

contracts/injective-cosmwasm-mock/src/msg.rs (1)
  • 7-112: The addition of new message types and queries related to trading activities is correctly implemented. Ensure that these new messages and queries are properly integrated and used throughout the contract to enhance its functionality for handling complex market operations.
packages/injective-cosmwasm/src/exchange/response.rs (1)
  • 102-102: The change to make aggregate_volumes an optional field in QueryAggregateVolumeResponse is correctly implemented. Ensure that this optionality is properly handled in the contract's logic to gracefully manage scenarios where no aggregate volumes are available.
contracts/injective-cosmwasm-mock/src/types.rs (1)
  • 1-170: The introduction of new Protobuf message types for orders and related operations is correctly implemented. Ensure that these types are properly integrated and used throughout the contract to facilitate interactions with the Injective Protocol for creating and managing spot and derivative orders.
contracts/injective-cosmwasm-mock/src/contract.rs (5)
  • 16-18: Constants CREATE_SPOT_ORDER_REPLY_ID and CREATE_DERIVATIVE_ORDER_REPLY_ID have been introduced to uniquely identify replies for spot and derivative order creations. This is a good practice as it helps in distinguishing between different types of replies in the contract's reply handler.
  • 20-20: The constant MSG_EXEC is introduced for specifying a message type. Ensure that this constant is used consistently wherever applicable to avoid hardcoding the string in multiple places, which can lead to errors if the string needs to be updated.
  • 30-51: The execute function's signature has been updated to handle new message types for testing transient spot and derivative orders. This is a significant enhancement as it allows for more comprehensive testing of the contract's functionality. Ensure that all new message types are properly validated within the function to prevent any potential misuse or errors.
  • 57-127: The query function has been expanded with new query message types, significantly enhancing the contract's querying capabilities. It's important to ensure that all new query types are thoroughly tested to validate their correctness and to check for any potential security implications, such as unauthorized access to sensitive information.
  • 132-136: The reply function has been updated to handle replies for creating spot and derivative orders. This is a crucial update for asynchronous order creation. It's important to ensure robust error handling for unrecognized reply IDs to prevent any unhandled cases that could lead to unexpected behavior.
contracts/injective-cosmwasm-mock/src/testing/query_exchange_derivative_tests.rs (9)
  • 23-42: The test test_query_perpetual_market_info properly sets up the environment, queries the perpetual market info, and asserts the expected results. It's good practice to ensure that the assertions are specific and cover all relevant aspects of the response to ensure the test is robust and meaningful.
  • 44-96: The test test_query_derivative_market demonstrates comprehensive testing of querying derivative market details. It includes setting up a market, querying it, and asserting various properties of the response. Ensure that edge cases, such as querying non-existent markets, are also covered to ensure the contract's robustness.
  • 98-129: The test test_query_effective_subaccount_position focuses on querying the effective position of a subaccount in a market. It's important to test both positive and negative scenarios, including cases where the subaccount has no position in the market, to fully validate the contract's behavior.
  • 131-172: The test test_query_vanilla_subaccount_position checks for the vanilla position of a subaccount in a market. Similar to the previous comment, ensure comprehensive coverage by including tests for various scenarios, such as empty positions and positions across multiple markets.
  • 174-219: The test test_query_trader_derivative_orders effectively queries and asserts the properties of derivative orders for a trader. It's crucial to also test the behavior when there are no orders for the trader or when invalid parameters are provided to ensure the contract handles these cases gracefully.
  • 221-239: The test test_query_perpetual_market_funding checks the funding state of a perpetual market. This is an important aspect of derivative markets. Ensure that the test covers various states of market funding, including scenarios where the market has undergone multiple funding intervals.
  • 241-258: The test test_query_derivative_market_mid_price_and_tob queries and asserts the mid-price and top of the book (TOB) for a derivative market. This test is crucial for ensuring that market data is accurately reported. Consider adding tests for markets with no orders to ensure the contract handles these scenarios correctly.
  • 260-309: The test test_query_derivative_market_orderbook provides a thorough examination of the order book for a derivative market. It's important to test various configurations of the order book, including empty order books and order books with a large number of orders, to ensure scalability and correctness.
  • 311-362: The test test_query_trader_transient_derivative_orders focuses on querying transient derivative orders. This test is particularly important for ensuring that transient orders are handled correctly. Ensure that the cleanup of transient orders is also tested to prevent any potential leaks or unintended persistence of data.
packages/injective-cosmwasm/src/querier.rs (2)
  • 12-12: The renaming of QueryAggregateVolumeResponse to QueryAggregateMarketVolumeResponse reflects a more specific naming convention that aligns with the functionality. This change improves code readability and clarity regarding the type of volume being queried.
  • 343-351: The implementation of query_aggregate_market_volume using the newly renamed QueryAggregateMarketVolumeResponse is correct and aligns with the renaming objective. Ensure that all references to the old response type have been updated across the codebase to maintain consistency.
contracts/injective-cosmwasm-mock/src/testing/query_exchange_tests.rs (4)
  • 50-63: The test test_exchange_params effectively queries and asserts the exchange parameters. It's well-structured and follows best practices for testing by asserting specific expected values. However, consider adding a brief comment explaining the significance of the values being asserted, such as why 604800 is expected for trading_rewards_vesting_duration, to improve maintainability and understandability for future contributors.
  • 145-153: The test test_query_spot_market_no_market_on_exchange is concise and directly tests the scenario where no market is available on the exchange. This is a good example of a focused test case. However, ensure that the market ID used (0xd5a22be807011d5e42d5b77da3f417e22676efae494109cd01c242ad46630115) is intentionally chosen for this test scenario and does not inadvertently reference a real or potentially valid market ID that could exist in a live or test environment.
  • 338-373: The test_query_market_volatility function correctly tests the market volatility query before and after adding new orders. However, the assertion that res.volatility equals Some(FPDecimal::ZERO) after adding new orders (line 373) might not always reflect realistic market conditions or the intended functionality of the volatility calculation. Ensure that this assertion accurately represents the expected outcome of the volatility query under the test conditions.
  • 438-448: The test test_query_market_atomic_execution_fee_multiplier effectively queries and asserts the atomic execution fee multiplier for a market. The assertion at line 448 is clear and directly related to the test's purpose. However, similar to other tests, ensure that the hardcoded value human_to_dec("0.0000025", QUOTE_DECIMALS) accurately reflects the expected multiplier under the test conditions. Additionally, consider documenting the rationale behind this expected value for clarity.
contracts/injective-cosmwasm-mock/src/utils.rs (5)
  • 1-7: The imports are well-organized and cover a broad range of functionalities required by the utility functions. It's good practice to keep imports tidy and grouped by their source or functionality, which has been done here.
  • 43-57: The UserInfo and Setup structs are well-defined and serve as foundational elements for setting up tests and simulations. However, it's important to ensure that all fields, especially those like market_id in Setup, are used appropriately throughout the code to avoid unused data.
Verification successful

The verification process has confirmed that market_id is utilized effectively in the code, particularly in functions related to launching markets, adding orders, and initializing liquidity. This indicates that market_id serves its intended purpose within the Setup struct and the overall application logic, facilitating the simulation of market conditions for testing purposes. Therefore, the initial review comment is consistent with the codebase as market_id is indeed used appropriately.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify that `market_id` is utilized effectively in the code.
rg 'market_id' contracts/injective-cosmwasm-mock/src/utils.rs

Length of output: 1788

* 59-63: The `ExchangeType` enum is a concise way to differentiate between spot, derivative, and none types. This approach simplifies decision-making in functions that depend on the type of exchange being simulated or tested. * 171-187: The `wasm_file` function dynamically constructs the path to the WASM file based on the contract name and architecture. This is a flexible approach, but ensure that the environment variable `ARTIFACTS_DIR_PATH` and the fallback directory `artifacts` are correctly configured in your CI/CD pipeline or local development environment. * 189-193: The `str_coin` function efficiently converts human-readable coin amounts to the `Coin` type expected by the Cosmos SDK. This utility function is crucial for simplifying the setup of account balances in tests. Ensure that the `human_to_dec` function, which it relies on, accurately handles various input formats.
packages/injective-cosmwasm/src/exchange_mock_querier.rs (1)
  • 191-197: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [194-209]

The change from using a vector directly to wrapping the vector in Some() for the aggregate_volumes field within the default_aggregate_account_volume_handler() function is a positive improvement. It introduces optionality to the data structure, which is more flexible and semantically correct for scenarios where there might be no aggregate volumes to report. This change enhances the function's ability to accurately represent possible states of aggregate volumes.

Comment on lines 67 to 141
fn test_query_subaccount_deposit() {
let env = Setup::new(ExchangeType::None);
let exchange = Exchange::new(&env.app);
let wasm = Wasm::new(&env.app);

let subaccount_id = checked_address_to_subaccount_id(&Addr::unchecked(env.users[0].account.address()), 1u32);

{
exchange
.deposit(
MsgDeposit {
sender: env.users[0].account.address(),
subaccount_id: subaccount_id.to_string(),
amount: Some(injective_std::types::cosmos::base::v1beta1::Coin {
amount: "10000000000000000000".to_string(),
denom: env.denoms["base"].clone(),
}),
},
&env.users[0].account,
)
.unwrap();
}

{
exchange
.deposit(
MsgDeposit {
sender: env.users[0].account.address(),
subaccount_id: subaccount_id.to_string(),
amount: Some(injective_std::types::cosmos::base::v1beta1::Coin {
amount: "100000000".to_string(),
denom: env.denoms["quote"].clone(),
}),
},
&env.users[0].account,
)
.unwrap();
}

let response = exchange
.query_subaccount_deposits(&QuerySubaccountDepositsRequest {
subaccount_id: subaccount_id.to_string(),
subaccount: None,
})
.unwrap();

assert_eq!(
response.deposits[&env.denoms["base"].clone()],
Deposit {
available_balance: human_to_proto("10.0", BASE_DECIMALS),
total_balance: human_to_proto("10.0", BASE_DECIMALS),
}
);
assert_eq!(
response.deposits[&env.denoms["quote"].clone()],
Deposit {
available_balance: human_to_proto("100.0", QUOTE_DECIMALS),
total_balance: human_to_proto("100.0", QUOTE_DECIMALS),
}
);

let query_msg = QueryMsg::TestSubAccountDepositQuery {
subaccount_id: subaccount_id.clone(),
denom: BASE_DENOM.to_string(),
};
let contract_response: SubaccountDepositResponse = wasm.query(&env.contract_address, &query_msg).unwrap();
assert_eq!(contract_response.deposits.total_balance, human_to_dec("10.0", BASE_DECIMALS));

let query_msg = QueryMsg::TestSubAccountDepositQuery {
subaccount_id: subaccount_id.clone(),
denom: QUOTE_DENOM.to_string(),
};
let contract_response: SubaccountDepositResponse = wasm.query(&env.contract_address, &query_msg).unwrap();
assert_eq!(contract_response.deposits.available_balance, human_to_dec("100.0", QUOTE_DECIMALS));
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the test test_query_subaccount_deposit, the setup and execution are well done, and the assertions are clear and directly related to the test's purpose. However, there's a potential improvement in readability and maintainability by extracting the deposit logic (lines 74-103) into a helper function, as it's repeated with minor variations. This would adhere to the DRY (Don't Repeat Yourself) principle and make the test code cleaner.

+ // Consider extracting this into a helper function for better code reuse and readability.

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
fn test_query_subaccount_deposit() {
let env = Setup::new(ExchangeType::None);
let exchange = Exchange::new(&env.app);
let wasm = Wasm::new(&env.app);
let subaccount_id = checked_address_to_subaccount_id(&Addr::unchecked(env.users[0].account.address()), 1u32);
{
exchange
.deposit(
MsgDeposit {
sender: env.users[0].account.address(),
subaccount_id: subaccount_id.to_string(),
amount: Some(injective_std::types::cosmos::base::v1beta1::Coin {
amount: "10000000000000000000".to_string(),
denom: env.denoms["base"].clone(),
}),
},
&env.users[0].account,
)
.unwrap();
}
{
exchange
.deposit(
MsgDeposit {
sender: env.users[0].account.address(),
subaccount_id: subaccount_id.to_string(),
amount: Some(injective_std::types::cosmos::base::v1beta1::Coin {
amount: "100000000".to_string(),
denom: env.denoms["quote"].clone(),
}),
},
&env.users[0].account,
)
.unwrap();
}
let response = exchange
.query_subaccount_deposits(&QuerySubaccountDepositsRequest {
subaccount_id: subaccount_id.to_string(),
subaccount: None,
})
.unwrap();
assert_eq!(
response.deposits[&env.denoms["base"].clone()],
Deposit {
available_balance: human_to_proto("10.0", BASE_DECIMALS),
total_balance: human_to_proto("10.0", BASE_DECIMALS),
}
);
assert_eq!(
response.deposits[&env.denoms["quote"].clone()],
Deposit {
available_balance: human_to_proto("100.0", QUOTE_DECIMALS),
total_balance: human_to_proto("100.0", QUOTE_DECIMALS),
}
);
let query_msg = QueryMsg::TestSubAccountDepositQuery {
subaccount_id: subaccount_id.clone(),
denom: BASE_DENOM.to_string(),
};
let contract_response: SubaccountDepositResponse = wasm.query(&env.contract_address, &query_msg).unwrap();
assert_eq!(contract_response.deposits.total_balance, human_to_dec("10.0", BASE_DECIMALS));
let query_msg = QueryMsg::TestSubAccountDepositQuery {
subaccount_id: subaccount_id.clone(),
denom: QUOTE_DENOM.to_string(),
};
let contract_response: SubaccountDepositResponse = wasm.query(&env.contract_address, &query_msg).unwrap();
assert_eq!(contract_response.deposits.available_balance, human_to_dec("100.0", QUOTE_DECIMALS));
}
fn test_query_subaccount_deposit() {
let env = Setup::new(ExchangeType::None);
let exchange = Exchange::new(&env.app);
let wasm = Wasm::new(&env.app);
let subaccount_id = checked_address_to_subaccount_id(&Addr::unchecked(env.users[0].account.address()), 1u32);
{
exchange
.deposit(
MsgDeposit {
sender: env.users[0].account.address(),
subaccount_id: subaccount_id.to_string(),
amount: Some(injective_std::types::cosmos::base::v1beta1::Coin {
amount: "10000000000000000000".to_string(),
denom: env.denoms["base"].clone(),
}),
},
&env.users[0].account,
)
.unwrap();
}
{
exchange
.deposit(
MsgDeposit {
sender: env.users[0].account.address(),
subaccount_id: subaccount_id.to_string(),
amount: Some(injective_std::types::cosmos::base::v1beta1::Coin {
amount: "100000000".to_string(),
denom: env.denoms["quote"].clone(),
}),
},
&env.users[0].account,
)
.unwrap();
}
// Consider extracting this into a helper function for better code reuse and readability.
let response = exchange
.query_subaccount_deposits(&QuerySubaccountDepositsRequest {
subaccount_id: subaccount_id.to_string(),
subaccount: None,
})
.unwrap();
assert_eq!(
response.deposits[&env.denoms["base"].clone()],
Deposit {
available_balance: human_to_proto("10.0", BASE_DECIMALS),
total_balance: human_to_proto("10.0", BASE_DECIMALS),
}
);
assert_eq!(
response.deposits[&env.denoms["quote"].clone()],
Deposit {
available_balance: human_to_proto("100.0", QUOTE_DECIMALS),
total_balance: human_to_proto("100.0", QUOTE_DECIMALS),
}
);
let query_msg = QueryMsg::TestSubAccountDepositQuery {
subaccount_id: subaccount_id.clone(),
denom: BASE_DENOM.to_string(),
};
let contract_response: SubaccountDepositResponse = wasm.query(&env.contract_address, &query_msg).unwrap();
assert_eq!(contract_response.deposits.total_balance, human_to_dec("10.0", BASE_DECIMALS));
let query_msg = QueryMsg::TestSubAccountDepositQuery {
subaccount_id: subaccount_id.clone(),
denom: QUOTE_DENOM.to_string(),
};
let contract_response: SubaccountDepositResponse = wasm.query(&env.contract_address, &query_msg).unwrap();
assert_eq!(contract_response.deposits.available_balance, human_to_dec("100.0", QUOTE_DECIMALS));
}

Comment on lines 638 to 671
pub fn execute_all_authorizations(app: &InjectiveTestApp, granter: &SigningAccount, grantee: String) {
create_generic_authorization(app, granter, grantee.clone(), MSG_CREATE_SPOT_LIMIT_ORDER_ENDPOINT.to_string(), None);
create_generic_authorization(
app,
granter,
grantee.clone(),
MSG_CREATE_DERIVATIVE_LIMIT_ORDER_ENDPOINT.to_string(),
None,
);

create_generic_authorization(
app,
granter,
grantee.clone(),
"/injective.exchange.v1beta1.MsgCreateDerivativeMarketOrder".to_string(),
None,
);

create_generic_authorization(
app,
granter,
grantee.clone(),
"/injective.exchange.v1beta1.MsgBatchUpdateOrders".to_string(),
None,
);

create_generic_authorization(app, granter, grantee, "/injective.exchange.v1beta1.MsgWithdraw".to_string(), None);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tip

Codebase Verification

The examination of the create_generic_authorization function reveals the use of .unwrap() on the result of GenericAuthorization::encode, indicating a potential for runtime panics in case of errors, which suggests a lack of comprehensive error handling in this part of the function. This finding aligns with the concern raised in the review comment about ensuring proper error handling within execute_all_authorizations to prevent potential runtime issues. Further details on the handling of other operations, such as the authz.grant call, were not provided, but the presence of .unwrap() already points to an area for improvement in error management.

Analysis chain

The execute_all_authorizations function demonstrates a comprehensive approach to setting up various authorizations. It's well-structured, but ensure that each create_generic_authorization call within it has proper error handling to prevent potential runtime issues.


To further verify the presence of error handling within the create_generic_authorization function, I will generate a new script to examine its implementation details.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify that error handling is implemented in `create_generic_authorization`.
rg 'create_generic_authorization' contracts/injective-cosmwasm-mock/src/utils.rs

Length of output: 570



Script:

#!/bin/bash
# Extract the body of `create_generic_authorization` to check for error handling mechanisms.
rg 'fn create_generic_authorization\(' -A 20 contracts/injective-cosmwasm-mock/src/utils.rs

Length of output: 845

Comment on lines 6 to 22
pub fn handle_crate_order_reply(deps: DepsMut<InjectiveQueryWrapper>, _msg: &Reply) -> Result<Response, ContractError> {
let mut response_str = "Something went wrong".to_string();

let querier: InjectiveQuerier = InjectiveQuerier::new(&deps.querier);

if let Some(mut cache) = ORDER_CALL_CACHE.may_load(deps.storage)? {
if !cache.is_empty() {
let order_info = &cache[0];
let response = querier.query_trader_transient_spot_orders(&order_info.market_id, &order_info.subaccount);
response_str = format!("{:?}", &response);
cache.clear();
ORDER_CALL_CACHE.save(deps.storage, &cache)?;
}
};

Ok(Response::new().add_event(Event::new("transient_order").add_attributes([("query_str", response_str)])))
}
Copy link

@coderabbitai coderabbitai bot Mar 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The function names handle_crate_order_reply and handle_crate_derivative_order_reply appear to contain a typo and should likely be renamed to handle_create_order_reply and handle_create_derivative_order_reply, respectively, to accurately reflect their purpose.

- pub fn handle_crate_order_reply
+ pub fn handle_create_order_reply
- pub fn handle_crate_derivative_order_reply
+ pub fn handle_create_derivative_order_reply

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
pub fn handle_crate_order_reply(deps: DepsMut<InjectiveQueryWrapper>, _msg: &Reply) -> Result<Response, ContractError> {
let mut response_str = "Something went wrong".to_string();
let querier: InjectiveQuerier = InjectiveQuerier::new(&deps.querier);
if let Some(mut cache) = ORDER_CALL_CACHE.may_load(deps.storage)? {
if !cache.is_empty() {
let order_info = &cache[0];
let response = querier.query_trader_transient_spot_orders(&order_info.market_id, &order_info.subaccount);
response_str = format!("{:?}", &response);
cache.clear();
ORDER_CALL_CACHE.save(deps.storage, &cache)?;
}
};
Ok(Response::new().add_event(Event::new("transient_order").add_attributes([("query_str", response_str)])))
}
pub fn handle_create_order_reply(deps: DepsMut<InjectiveQueryWrapper>, _msg: &Reply) -> Result<Response, ContractError> {
let mut response_str = "Something went wrong".to_string();
let querier: InjectiveQuerier = InjectiveQuerier::new(&deps.querier);
if let Some(mut cache) = ORDER_CALL_CACHE.may_load(deps.storage)? {
if !cache.is_empty() {
let order_info = &cache[0];
let response = querier.query_trader_transient_spot_orders(&order_info.market_id, &order_info.subaccount);
response_str = format!("{:?}", &response);
cache.clear();
ORDER_CALL_CACHE.save(deps.storage, &cache)?;
}
};
Ok(Response::new().add_event(Event::new("transient_order").add_attributes([("query_str", response_str)])))
}

Ensure proper error handling for all operations that can fail, such as unwrap() calls, to prevent potential runtime panics. Consider using match statements or ? operator to handle errors gracefully.

Also applies to: 24-38

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is good suggestion!

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@maxrobot: I'm glad you found the suggestion helpful! If you have any more questions or need further assistance as you implement these changes, feel free to ask. Happy coding!

(_/)
( •_•)
/>🥕

Comment on lines 376 to 410
#[test]
#[cfg_attr(not(feature = "integration"), ignore)]
fn test_query_aggregate_market_volume() {
let env = Setup::new(ExchangeType::Spot);
let wasm = Wasm::new(&env.app);
let market_id = env.market_id.unwrap();

add_spot_initial_liquidity(&env.app, market_id.clone());

let query_msg = QueryMsg::TestAggregateMarketVolume {
market_id: MarketId::new(market_id.clone()).unwrap(),
};

let res: QueryAggregateMarketVolumeResponse = wasm.query(&env.contract_address, &query_msg).unwrap();
assert_eq!(res.volume.clone().unwrap().maker_volume, "0");
assert_eq!(res.volume.clone().unwrap().taker_volume, "0");

// consume liquidity
let new_orders: Vec<HumanOrder> = vec![
HumanOrder {
price: "10.1".to_string(),
quantity: "10".to_string(),
order_type: OrderType::Buy,
},
HumanOrder {
price: "9.9".to_string(),
quantity: "5".to_string(),
order_type: OrderType::Sell,
},
];

add_spot_orders(&env.app, market_id.clone(), new_orders);
let res: QueryAggregateMarketVolumeResponse = wasm.query(&env.contract_address, &query_msg).unwrap();
assert_eq!(res.volume.clone().unwrap().maker_volume, "150500000");
assert_eq!(res.volume.clone().unwrap().taker_volume, "150500000");
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test_query_aggregate_market_volume function is well-structured and tests the aggregate market volume effectively. However, the hardcoded values for maker_volume and taker_volume (lines 409-410) assume specific outcomes based on the test setup. It's crucial to ensure that these values accurately reflect the expected volumes given the test's market conditions and order executions. Additionally, consider adding comments to explain how these expected values are derived to improve the test's readability and maintainability.

Comment on lines 412 to 435

#[test]
#[cfg_attr(not(feature = "integration"), ignore)]
fn test_query_aggregate_account_volume() {
let env = Setup::new(ExchangeType::Spot);
let wasm = Wasm::new(&env.app);
let market_id = env.market_id.unwrap();

add_spot_initial_liquidity(&env.app, market_id.clone());

let query_msg = QueryMsg::TestAggregateAccountVolume {
account_id: env.users[1].subaccount_id.to_string(),
};

let res: QueryAggregateVolumeResponse = wasm.query(&env.contract_address, &query_msg).unwrap();
assert!(res.aggregate_volumes.is_none());

let (price, quantity) = scale_price_quantity_for_spot_market("9.9", "1", &BASE_DECIMALS, &QUOTE_DECIMALS);
add_spot_order_as(&env.app, market_id.clone(), &env.users[1], price, quantity, OrderType::Sell);

let res: QueryAggregateVolumeResponse = wasm.query(&env.contract_address, &query_msg).unwrap();
let volume: &VolumeByType = &res.aggregate_volumes.unwrap()[0].volume;
assert_eq!(volume.maker_volume, FPDecimal::ZERO);
assert_eq!(volume.taker_volume, human_to_dec("9.9", QUOTE_DECIMALS));
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In test_query_aggregate_account_volume, the test setup and execution are clear, and the use of scale_price_quantity_for_spot_market for order creation is appropriate. However, the assertion that volume.taker_volume equals human_to_dec("9.9", QUOTE_DECIMALS) (line 435) directly ties the test's success to specific scaling logic. Ensure that this logic is consistently applied across all tests and accurately reflects the intended behavior of the contract's volume calculation.

Comment on lines 461 to 495
fn test_query_trader_transient_spot_orders() {
let env = Setup::new(ExchangeType::Spot);
let wasm = Wasm::new(&env.app);
let market_id = env.market_id.unwrap();

let subaccount_id = checked_address_to_subaccount_id(&Addr::unchecked(env.users[0].account.address()), 0u32);

execute_all_authorizations(&env.app, &env.users[0].account, env.contract_address.clone());
add_spot_initial_liquidity(&env.app, market_id.clone());

let (scale_price, scale_quantity) = scale_price_quantity_for_spot_market_dec("9.8", "1", &BASE_DECIMALS, &QUOTE_DECIMALS);

let res = wasm
.execute(
&env.contract_address,
&ExecuteMsg::TestTraderTransientSpotOrders {
market_id: MarketId::new(market_id).unwrap(),
subaccount_id: subaccount_id.clone(),
price: scale_price.to_string(),
quantity: scale_quantity.to_string(),
},
&[],
&env.users[0].account,
)
.unwrap();

let transient_query = res
.events
.iter()
.find(|e| e.ty == "wasm-transient_order")
.and_then(|event| event.attributes.iter().find(|a| a.key == "query_str"));

assert!(transient_query.is_some());
let expected_order_info = "TraderSpotOrdersResponse { orders: Some([TrimmedSpotLimitOrder { price: FPDecimal { num: 9800000, sign: 1 }, quantity: FPDecimal { num: 1000000000000000000000000000000000000, sign: 1 }";
assert!(transient_query.unwrap().value.contains(expected_order_info));
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test test_query_trader_transient_spot_orders demonstrates a complex scenario involving transient spot orders. The use of events to verify the outcome is a good practice. However, the assertion at line 493-495 relies on a string match that might be brittle if the event format changes. Consider using a more structured approach to parse and verify the event data to improve the test's robustness against changes in event formatting.

- assert!(transient_query.unwrap().value.contains(expected_order_info));
+ // Suggestion: Parse the event data into a structured format and assert on the parsed data.

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
fn test_query_trader_transient_spot_orders() {
let env = Setup::new(ExchangeType::Spot);
let wasm = Wasm::new(&env.app);
let market_id = env.market_id.unwrap();
let subaccount_id = checked_address_to_subaccount_id(&Addr::unchecked(env.users[0].account.address()), 0u32);
execute_all_authorizations(&env.app, &env.users[0].account, env.contract_address.clone());
add_spot_initial_liquidity(&env.app, market_id.clone());
let (scale_price, scale_quantity) = scale_price_quantity_for_spot_market_dec("9.8", "1", &BASE_DECIMALS, &QUOTE_DECIMALS);
let res = wasm
.execute(
&env.contract_address,
&ExecuteMsg::TestTraderTransientSpotOrders {
market_id: MarketId::new(market_id).unwrap(),
subaccount_id: subaccount_id.clone(),
price: scale_price.to_string(),
quantity: scale_quantity.to_string(),
},
&[],
&env.users[0].account,
)
.unwrap();
let transient_query = res
.events
.iter()
.find(|e| e.ty == "wasm-transient_order")
.and_then(|event| event.attributes.iter().find(|a| a.key == "query_str"));
assert!(transient_query.is_some());
let expected_order_info = "TraderSpotOrdersResponse { orders: Some([TrimmedSpotLimitOrder { price: FPDecimal { num: 9800000, sign: 1 }, quantity: FPDecimal { num: 1000000000000000000000000000000000000, sign: 1 }";
assert!(transient_query.unwrap().value.contains(expected_order_info));
assert!(transient_query.is_some());
let expected_order_info = "TraderSpotOrdersResponse { orders: Some([TrimmedSpotLimitOrder { price: FPDecimal { num: 9800000, sign: 1 }, quantity: FPDecimal { num: 1000000000000000000000000000000000000, sign: 1 }";
// Suggestion: Parse the event data into a structured format and assert on the parsed data.

Comment on lines +7 to +12
pub fn create_stargate_msg(type_url: &str, value: Vec<u8>) -> StdResult<CosmosMsg<InjectiveMsgWrapper>> {
Ok(CosmosMsg::Stargate {
type_url: type_url.to_string(),
value: value.into(),
})
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure proper error handling for all operations that can fail, such as unwrap() calls, to prevent potential runtime panics. Consider using match statements or ? operator to handle errors gracefully, especially when encoding messages and creating orders.

Also applies to: 14-36, 38-64, 66-70

contracts/injective-cosmwasm-mock/src/handle.rs Outdated Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Status

Actionable comments generated: 3

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 50f00df and 7b08898.
Files selected for processing (7)
  • contracts/injective-cosmwasm-mock/src/contract.rs (2 hunks)
  • contracts/injective-cosmwasm-mock/src/msg.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/authz.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/mod.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/query_exchange_derivative_tests.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/query_exchange_tests.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/utils.rs (1 hunks)
Files skipped from review as they are similar to previous changes (4)
  • contracts/injective-cosmwasm-mock/src/msg.rs
  • contracts/injective-cosmwasm-mock/src/testing/mod.rs
  • contracts/injective-cosmwasm-mock/src/testing/query_exchange_derivative_tests.rs
  • contracts/injective-cosmwasm-mock/src/testing/query_exchange_tests.rs
Additional comments: 4
contracts/injective-cosmwasm-mock/src/contract.rs (3)
  • 16-21: The addition of new constants for reply IDs and message types (CREATE_SPOT_ORDER_REPLY_ID, CREATE_DERIVATIVE_ORDER_REPLY_ID, and MSG_EXEC) is clear and follows the Rust convention for constant naming. These constants are crucial for identifying different types of messages and replies within the contract, enhancing readability and maintainability.
  • 29-51: The execute function signature has been updated to handle new message types for transient spot and derivative orders. This update is crucial for expanding the contract's functionality to support more complex market operations. The match statement is well-structured, ensuring that each message type is handled appropriately.
  • 39-51: The addition of new functions handle_test_transient_spot_order and handle_test_transient_derivative_order within the execute function enhances the contract's capabilities to manage transient orders for spot and derivative markets. This is a significant improvement, aligning with the PR's objectives to expand testing coverage and functionality for complex market operations.
contracts/injective-cosmwasm-mock/src/utils.rs (1)
  • 43-63: The introduction of the UserInfo and Setup structures, along with the ExchangeType enum, significantly improves the organization and readability of the code. These structures facilitate the setup and management of testing environments, making it easier to simulate different market scenarios. This is a positive change that enhances the maintainability and scalability of the testing framework.

contracts/injective-cosmwasm-mock/src/testing/authz.rs Outdated Show resolved Hide resolved
contracts/injective-cosmwasm-mock/src/testing/authz.rs Outdated Show resolved Hide resolved
Copy link
Contributor

@maxrobot maxrobot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please see comments.

In addition can you please:

  1. break the tests into logical files e.g. test_{modules}.rs
  2. make functions for the queries not just slap the queries in the contract.rs as it is offensive to look at IMO
  3. make sure names are spelt correct this is for files, functions and variables
    (this repo is public fyi)

Comment on lines 41 to 43
thiserror = { version = "1.0.56" }
protobuf = "3.3.0"
prost = "0.11.9"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

autoformatter plz

contracts/injective-cosmwasm-mock/Cargo.toml Outdated Show resolved Hide resolved
}
}

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn query(deps: Deps<InjectiveQueryWrapper>, _env: Env, msg: QueryMsg) -> StdResult<Binary> {
let querier = InjectiveQuerier::new(&deps.querier);
let querier: InjectiveQuerier = InjectiveQuerier::new(&deps.querier);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this definition is useless don't make me get @gorgos!

Comment on lines 27 to 28
FPDecimal::must_from_str(price.as_str()).scaled(EXCHANGE_DECIMALS),
FPDecimal::must_from_str(quantity.as_str()).scaled(EXCHANGE_DECIMALS),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this scaling is incorrect but for the purposes of these tests I don't think it actually matters

contracts/injective-cosmwasm-mock/src/handle.rs Outdated Show resolved Hide resolved
Comment on lines 4 to 13
#[cfg(test)]
mod testing;

mod handle;
mod order_management;
mod reply;
mod state;
mod types;
#[cfg(test)]
pub mod utils;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

make this tidier

contracts/injective-cosmwasm-mock/src/msg.rs Outdated Show resolved Hide resolved
Comment on lines 6 to 22
pub fn handle_crate_order_reply(deps: DepsMut<InjectiveQueryWrapper>, _msg: &Reply) -> Result<Response, ContractError> {
let mut response_str = "Something went wrong".to_string();

let querier: InjectiveQuerier = InjectiveQuerier::new(&deps.querier);

if let Some(mut cache) = ORDER_CALL_CACHE.may_load(deps.storage)? {
if !cache.is_empty() {
let order_info = &cache[0];
let response = querier.query_trader_transient_spot_orders(&order_info.market_id, &order_info.subaccount);
response_str = format!("{:?}", &response);
cache.clear();
ORDER_CALL_CACHE.save(deps.storage, &cache)?;
}
};

Ok(Response::new().add_event(Event::new("transient_order").add_attributes([("query_str", response_str)])))
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is good suggestion!

contracts/injective-cosmwasm-mock/src/testing/authz.rs Outdated Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Status

Actionable comments generated: 16

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 7b08898 and 9443f46.
Files ignored due to path filters (2)
  • Cargo.lock is excluded by: !**/*.lock
  • contracts/injective-cosmwasm-mock/Cargo.toml is excluded by: !**/*.toml
Files selected for processing (12)
  • contracts/injective-cosmwasm-mock/src/contract.rs (2 hunks)
  • contracts/injective-cosmwasm-mock/src/handle.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/lib.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/msg.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/query.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/reply.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/mod.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/test_authz.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/test_exchange.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/test_exchange_derivative.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/test_oracle.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/utils.rs (1 hunks)
Files skipped from review as they are similar to previous changes (4)
  • contracts/injective-cosmwasm-mock/src/handle.rs
  • contracts/injective-cosmwasm-mock/src/lib.rs
  • contracts/injective-cosmwasm-mock/src/msg.rs
  • contracts/injective-cosmwasm-mock/src/reply.rs
Additional comments: 19
contracts/injective-cosmwasm-mock/src/testing/mod.rs (1)
  • 1-4: The module declarations are correctly formatted and follow Rust conventions. It's good practice to keep module names descriptive and concise, which has been achieved here. The renaming and addition of new modules indicate an expansion of testing capabilities, aligning with the PR's objectives.
contracts/injective-cosmwasm-mock/src/testing/test_authz.rs (1)
  • 1-10: The imports and utility functions are correctly used and relevant to the tests being implemented. It's important to ensure that imports remain organized and only include what's necessary for the file's functionality to maintain readability and performance.
contracts/injective-cosmwasm-mock/src/testing/test_oracle.rs (2)
  • 1-8: The imports and utility functions are correctly used and relevant to the tests being implemented. Organizing imports and ensuring only necessary modules are included is key to maintaining code readability and performance.
  • 45-73: The test_query_oracle_volatility function follows a similar pattern to the previous test, correctly setting up and executing the test. The assertions at the end validate the absence of volatility and raw history in the response, which aligns with the expected behavior. This test demonstrates good practice by explicitly checking for the expected null values in the response.
contracts/injective-cosmwasm-mock/src/query.rs (1)
  • 1-155: All query handler functions are correctly implemented, following a consistent pattern of converting query results to binary format using to_json_binary. This consistency is good for maintainability and readability. However, it's important to ensure that error handling is robust, especially when dealing with external data or queries that might fail. Consider adding more detailed error handling or logging to improve the resilience and debuggability of the contract.

Consider enhancing error handling in query functions to provide more detailed feedback in case of failures, which could improve debugging and resilience.

contracts/injective-cosmwasm-mock/src/contract.rs (2)
  • 1-16: The file's structure and organization are well-maintained, with clear separation between imports, constants, and function definitions. The introduction of new constants for reply IDs and message types is correctly implemented, enhancing the contract's functionality and readability.
  • 33-151: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [18-149]

The updates to function signatures and the addition of new functions for handling transient spot and derivative orders are correctly implemented. However, ensure that all new message types and reply IDs are thoroughly tested to prevent any unexpected behavior. Additionally, consider adding more detailed comments or documentation to new functions to improve maintainability and understandability for future contributors.

Consider adding more detailed comments or documentation to new functions, enhancing maintainability and clarity for future contributors.

contracts/injective-cosmwasm-mock/src/testing/test_exchange_derivative.rs (2)
  • 1-22: The imports and utility functions are correctly used and relevant to the tests being implemented. Keeping imports organized and including only necessary modules is key to maintaining code readability and performance.
  • 23-239: The test functions are well-structured, setting up the testing environment and querying various aspects of the derivative market. The assertions at the end of each test ensure that the expected behavior matches the actual behavior, which is a good practice in testing. However, ensure that all new functionality introduced in these tests is thoroughly tested to prevent any unexpected behavior. Additionally, consider adding more detailed comments or documentation to new test functions to improve maintainability and understandability for future contributors.

Consider adding more detailed comments or documentation to new test functions, enhancing maintainability and clarity for future contributors.

contracts/injective-cosmwasm-mock/src/testing/test_exchange.rs (10)
  • 25-44: The test function test_msg_deposit correctly sets up the environment, executes a deposit message, and asserts the success of the operation. However, it's important to ensure that the error message in the assertion provides enough context for debugging in case of failure. Consider enhancing the error message to include more details about the failure.
  • 47-61: The test function test_exchange_params effectively queries and asserts the correctness of exchange parameters. It's well-structured and follows best practices for testing. Ensure that the hardcoded values, such as the listing fee and trading rewards vesting duration, are aligned with the expected values from the contract's business logic or configuration.
  • 64-127: The test function test_query_subaccount_deposit correctly performs deposit operations and queries to assert the correctness of the deposit amounts. It's important to ensure that the deposit amounts and denominations used in the test are representative of real-world scenarios to ensure the test's relevance. Additionally, consider adding negative test cases to cover scenarios where queries might fail or return unexpected results.
  • 129-139: The test function test_query_spot_market_no_market_on_exchange correctly queries for a non-existent spot market and asserts the expected response. This test is crucial for ensuring the contract's robustness in handling queries for non-existent markets. Consider adding a comment to explain the significance of the hardcoded market ID used in the test, ensuring future maintainability.
  • 184-239: The test function test_query_trader_spot_orders correctly adds spot orders and queries to assert the correctness of the orders' details. The assertions are detailed, ensuring the accuracy of price, quantity, and order type. However, the test could be improved by adding assertions for the order hash to ensure its correctness. Additionally, consider adding tests for edge cases, such as querying orders for a trader with no orders or querying orders in a non-existent market.
  • 243-259: The test function test_query_spot_market_mid_price_and_tob effectively adds initial liquidity and queries to assert the correctness of the mid-price and TOB. The assertions are precise and cover the expected values for the mid-price, best buy price, and best sell price. Ensure that the liquidity addition is representative of realistic market conditions to ensure the test's relevance. Additionally, consider adding negative test cases to cover scenarios where the market is empty or the liquidity is skewed.
  • 324-359: The test function test_query_market_volatility correctly adds orders and queries to assert the correctness of the market volatility calculation. The initial assertion of None volatility followed by an assertion of Some(FPDecimal::ZERO) after adding orders demonstrates the test's intent to verify the volatility calculation's sensitivity to market activity. Ensure that the test covers a range of market conditions, including high volatility scenarios, to fully validate the volatility calculation logic.
  • 362-396: The test function test_query_aggregate_market_volume effectively adds orders and queries to assert the correctness of the aggregate maker and taker volumes. The test transitions from an initial state with zero volumes to a state with non-zero volumes after order additions, effectively demonstrating the query's ability to aggregate market volumes. Consider adding more diverse test cases to cover different types of market activities and their impact on aggregate volumes to ensure comprehensive testing of the volume aggregation logic.
  • 399-421: The test function test_query_aggregate_account_volume correctly adds an order for a specific account and queries to assert the correctness of the aggregate volumes for that account. The test effectively demonstrates the query's ability to aggregate volumes on a per-account basis. However, the test could be enhanced by covering scenarios where multiple accounts contribute to the market's volume, ensuring the query logic accurately aggregates volumes across different accounts.
  • 424-434: The test function test_query_market_atomic_execution_fee_multiplier correctly queries to assert the correctness of the market atomic execution fee multiplier. The assertion checks the multiplier value against a hardcoded expected value. Ensure that this hardcoded value is aligned with the contract's configuration or business logic. Additionally, consider adding tests to cover changes in the multiplier value under different market conditions or configurations, if applicable.

Comment on lines 11 to 31
#[test]
#[cfg_attr(not(feature = "integration"), ignore)]
fn test_query_grants() {
let env = Setup::new(ExchangeType::None);
let wasm = Wasm::new(&env.app);

let msg_type_url = "/injective.exchange.v1beta1.MsgCreateDerivativeMarketOrder".to_string();
let granter = &env.users[0].account;
let grantee = env.contract_address.clone();

create_generic_authorization(&env.app, granter, grantee.to_owned(), msg_type_url.to_owned(), None);

let query_msg = QueryMsg::TestQueryGrants {
grantee,
granter: granter.address(),
msg_type_url,
pagination: None,
};
let _res: RunnerResult<GrantsResponse> = wasm.query(&env.contract_address, &query_msg);
//todo fix query
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test_query_grants function correctly sets up the testing environment, creates a generic authorization, and queries for grants. However, there's a //todo fix query comment indicating that the query part might need further implementation or fixing. It's crucial to address any TODOs before merging to ensure the test is complete and functional.

-    //todo fix query
+    // Ensure the query is correctly implemented and tested.

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
#[test]
#[cfg_attr(not(feature = "integration"), ignore)]
fn test_query_grants() {
let env = Setup::new(ExchangeType::None);
let wasm = Wasm::new(&env.app);
let msg_type_url = "/injective.exchange.v1beta1.MsgCreateDerivativeMarketOrder".to_string();
let granter = &env.users[0].account;
let grantee = env.contract_address.clone();
create_generic_authorization(&env.app, granter, grantee.to_owned(), msg_type_url.to_owned(), None);
let query_msg = QueryMsg::TestQueryGrants {
grantee,
granter: granter.address(),
msg_type_url,
pagination: None,
};
let _res: RunnerResult<GrantsResponse> = wasm.query(&env.contract_address, &query_msg);
//todo fix query
}
#[test]
#[cfg_attr(not(feature = "integration"), ignore)]
fn test_query_grants() {
let env = Setup::new(ExchangeType::None);
let wasm = Wasm::new(&env.app);
let msg_type_url = "/injective.exchange.v1beta1.MsgCreateDerivativeMarketOrder".to_string();
let granter = &env.users[0].account;
let grantee = env.contract_address.clone();
create_generic_authorization(&env.app, granter, grantee.to_owned(), msg_type_url.to_owned(), None);
let query_msg = QueryMsg::TestQueryGrants {
grantee,
granter: granter.address(),
msg_type_url,
pagination: None,
};
let _res: RunnerResult<GrantsResponse> = wasm.query(&env.contract_address, &query_msg);
// Ensure the query is correctly implemented and tested.
}

Comment on lines 9 to 43
#[test]
#[cfg_attr(not(feature = "integration"), ignore)]
fn test_query_oracle_price() {
let env = Setup::new(ExchangeType::None);
let wasm = Wasm::new(&env.app);
let oracle = Oracle::new(&env.app);

let query_msg = QueryMsg::TestQueryOraclePrice {
oracle_type: OracleType::PriceFeed,
base: env.denoms["base"].to_owned(),
quote: env.denoms["quote"].to_owned(),
};

let query_oracle_price_request = QueryOraclePriceRequest {
oracle_type: 2i32,
base: env.denoms["base"].to_owned(),
quote: env.denoms["quote"].to_owned(),
};

let oracle_response = oracle.query_oracle_price(&query_oracle_price_request);
let contract_response: RunnerResult<OraclePriceResponse> = wasm.query(&env.contract_address, &query_msg);

let oracle_response_pair_state = oracle_response.unwrap().price_pair_state;
let contract_response_pair_state = contract_response.unwrap().price_pair_state;

assert!(contract_response_pair_state.is_some());
assert!(oracle_response_pair_state.is_some());
let oracle_response_pair_state = oracle_response_pair_state.unwrap();
let contract_response_pair_state = contract_response_pair_state.unwrap();

let oracle_response_pair_price = FPDecimal::must_from_str(oracle_response_pair_state.pair_price.as_str());

assert_eq!(contract_response_pair_state.pair_price.scaled(18), oracle_response_pair_price);
assert_eq!(contract_response_pair_state.pair_price.scaled(18), oracle_response_pair_price);
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test_query_oracle_price function is well-structured, setting up the testing environment and querying oracle prices. The assertions at the end of the test ensure that the expected behavior matches the actual behavior, which is a good practice in testing. However, the repeated assertion in lines 41 and 42 seems to be a mistake. It's important to ensure that each assertion tests a unique aspect of the response.

-    assert_eq!(contract_response_pair_state.pair_price.scaled(18), oracle_response_pair_price);

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
#[test]
#[cfg_attr(not(feature = "integration"), ignore)]
fn test_query_oracle_price() {
let env = Setup::new(ExchangeType::None);
let wasm = Wasm::new(&env.app);
let oracle = Oracle::new(&env.app);
let query_msg = QueryMsg::TestQueryOraclePrice {
oracle_type: OracleType::PriceFeed,
base: env.denoms["base"].to_owned(),
quote: env.denoms["quote"].to_owned(),
};
let query_oracle_price_request = QueryOraclePriceRequest {
oracle_type: 2i32,
base: env.denoms["base"].to_owned(),
quote: env.denoms["quote"].to_owned(),
};
let oracle_response = oracle.query_oracle_price(&query_oracle_price_request);
let contract_response: RunnerResult<OraclePriceResponse> = wasm.query(&env.contract_address, &query_msg);
let oracle_response_pair_state = oracle_response.unwrap().price_pair_state;
let contract_response_pair_state = contract_response.unwrap().price_pair_state;
assert!(contract_response_pair_state.is_some());
assert!(oracle_response_pair_state.is_some());
let oracle_response_pair_state = oracle_response_pair_state.unwrap();
let contract_response_pair_state = contract_response_pair_state.unwrap();
let oracle_response_pair_price = FPDecimal::must_from_str(oracle_response_pair_state.pair_price.as_str());
assert_eq!(contract_response_pair_state.pair_price.scaled(18), oracle_response_pair_price);
assert_eq!(contract_response_pair_state.pair_price.scaled(18), oracle_response_pair_price);
}
#[test]
#[cfg_attr(not(feature = "integration"), ignore)]
fn test_query_oracle_price() {
let env = Setup::new(ExchangeType::None);
let wasm = Wasm::new(&env.app);
let oracle = Oracle::new(&env.app);
let query_msg = QueryMsg::TestQueryOraclePrice {
oracle_type: OracleType::PriceFeed,
base: env.denoms["base"].to_owned(),
quote: env.denoms["quote"].to_owned(),
};
let query_oracle_price_request = QueryOraclePriceRequest {
oracle_type: 2i32,
base: env.denoms["base"].to_owned(),
quote: env.denoms["quote"].to_owned(),
};
let oracle_response = oracle.query_oracle_price(&query_oracle_price_request);
let contract_response: RunnerResult<OraclePriceResponse> = wasm.query(&env.contract_address, &query_msg);
let oracle_response_pair_state = oracle_response.unwrap().price_pair_state;
let contract_response_pair_state = contract_response.unwrap().price_pair_state;
assert!(contract_response_pair_state.is_some());
assert!(oracle_response_pair_state.is_some());
let oracle_response_pair_state = oracle_response_pair_state.unwrap();
let contract_response_pair_state = contract_response_pair_state.unwrap();
let oracle_response_pair_price = FPDecimal::must_from_str(oracle_response_pair_state.pair_price.as_str());
assert_eq!(contract_response_pair_state.pair_price.scaled(18), oracle_response_pair_price);
}

Comment on lines +142 to +179
#[test]
#[cfg_attr(not(feature = "integration"), ignore)]
fn test_query_spot_market() {
let env = Setup::new(ExchangeType::None);
let wasm = Wasm::new(&env.app);
let exchange = Exchange::new(&env.app);

// Instantiate spot market
let ticker = "INJ/USDT".to_string();
let min_price_tick_size = FPDecimal::must_from_str("0.000000000000001");
let min_quantity_tick_size = FPDecimal::must_from_str("1000000000000000");

exchange
.instant_spot_market_launch(
MsgInstantSpotMarketLaunch {
sender: env.signer.address(),
ticker: ticker.clone(),
base_denom: BASE_DENOM.to_string(),
quote_denom: QUOTE_DENOM.to_string(),
min_price_tick_size: dec_to_proto(min_price_tick_size),
min_quantity_tick_size: dec_to_proto(min_quantity_tick_size),
},
&env.signer,
)
.unwrap();

let spot_market_id = get_spot_market_id(&exchange, ticker.to_owned());

// Query
let market_id = MarketId::new(spot_market_id.clone()).unwrap();
let query_msg = QueryMsg::TestSpotMarketQuery { market_id };
let res: SpotMarketResponse = wasm.query(&env.contract_address, &query_msg).unwrap();

let response_market = res.market.unwrap();
assert_eq!(response_market.market_id.as_str(), spot_market_id);
assert_eq!(response_market.ticker.as_str(), ticker);
assert_eq!(response_market.base_denom.as_str(), BASE_DENOM);
assert_eq!(response_market.quote_denom.as_str(), QUOTE_DENOM);
assert_eq!(response_market.min_price_tick_size.clone().to_string(), min_price_tick_size.to_string());
assert_eq!(response_market.min_quantity_tick_size.to_string(), min_quantity_tick_size.to_string());
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test function test_query_spot_market effectively sets up a spot market and queries to assert the correctness of the market details. The assertions are comprehensive, covering all relevant market details. Ensure that the hardcoded values, such as the ticker and tick sizes, are aligned with the expected market configurations. Additionally, consider abstracting the market setup into a reusable function if similar setup steps are used across multiple test functions, to improve code maintainability and reduce duplication.

// Suggested refactor: Abstract market setup into a reusable function.
fn setup_spot_market(env: &Setup, ticker: String, min_price_tick_size: FPDecimal, min_quantity_tick_size: FPDecimal) -> String {
    let exchange = Exchange::new(&env.app);
    exchange.instant_spot_market_launch(
        MsgInstantSpotMarketLaunch {
            sender: env.signer.address(),
            ticker: ticker.clone(),
            base_denom: BASE_DENOM.to_string(),
            quote_denom: QUOTE_DENOM.to_string(),
            min_price_tick_size: dec_to_proto(min_price_tick_size),
            min_quantity_tick_size: dec_to_proto(min_quantity_tick_size),
        },
        &env.signer,
    ).unwrap();
    get_spot_market_id(&exchange, ticker)
}

Comment on lines +262 to +319
#[test]
#[cfg_attr(not(feature = "integration"), ignore)]
fn test_query_spot_market_orderbook() {
let env = Setup::new(ExchangeType::Spot);
let wasm = Wasm::new(&env.app);
let market_id = env.market_id.unwrap();

let liquidity_orders = get_initial_liquidity_orders_vector();
add_spot_orders(&env.app, market_id.clone(), liquidity_orders.clone());

let query_msg = QueryMsg::TestSpotMarketOrderbook {
market_id: MarketId::new(market_id.clone()).unwrap(),
side: OrderSide::Unspecified,
limit_cumulative_quantity: None,
limit_cumulative_notional: None,
};

let res: QueryOrderbookResponse = wasm.query(&env.contract_address, &query_msg).unwrap();
let buys_price_level = res.buys_price_level;
let sells_price_level = res.sells_price_level;
assert_eq!(buys_price_level.len(), 4);
assert_eq!(sells_price_level.len(), 4);
assert_eq!(
buys_price_level[0],
PriceLevel {
p: human_to_dec(liquidity_orders[sells_price_level.len()].price.as_str(), QUOTE_DECIMALS - BASE_DECIMALS),
q: human_to_dec(liquidity_orders[sells_price_level.len()].quantity.as_str(), BASE_DECIMALS),
}
);
assert_eq!(
buys_price_level[1],
PriceLevel {
p: human_to_dec(
liquidity_orders[sells_price_level.len() + 1].price.as_str(),
QUOTE_DECIMALS - BASE_DECIMALS
),
q: human_to_dec(liquidity_orders[sells_price_level.len() + 1].quantity.as_str(), BASE_DECIMALS),
}
);

assert_eq!(
sells_price_level[0],
PriceLevel {
p: human_to_dec(
liquidity_orders[sells_price_level.len() - 1].price.as_str(),
QUOTE_DECIMALS - BASE_DECIMALS
),
q: human_to_dec(liquidity_orders[sells_price_level.len() - 1].quantity.as_str(), BASE_DECIMALS),
}
);
assert_eq!(
sells_price_level[1],
PriceLevel {
p: human_to_dec(
liquidity_orders[sells_price_level.len() - 2].price.as_str(),
QUOTE_DECIMALS - BASE_DECIMALS
),
q: human_to_dec(liquidity_orders[sells_price_level.len() - 2].quantity.as_str(), BASE_DECIMALS),
}
);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test function test_query_spot_market_orderbook correctly adds orders and queries to assert the correctness of the orderbook's buy and sell price levels. The assertions are comprehensive, covering both buy and sell sides of the orderbook. However, the logic to assert the price levels seems to rely on the length of the sells_price_level array for indexing into the liquidity_orders array, which could lead to confusion or errors if the orderbook structure changes. Consider using more explicit and robust indexing or referencing mechanisms to improve code clarity and maintainability.

Comment on lines 437 to 443
#[test]
#[cfg_attr(not(feature = "integration"), ignore)]
fn test_query_spot_orders_to_cancel_up_to_amount() {}

#[test]
#[cfg_attr(not(feature = "integration"), ignore)]
fn test_query_derivative_orders_to_cancel_up_to_amount() {}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test functions test_query_spot_orders_to_cancel_up_to_amount and test_query_derivative_orders_to_cancel_up_to_amount are currently placeholders without implementation. It's important to implement these tests to ensure coverage of order cancellation scenarios, which are critical for the contract's functionality. Consider adding the necessary test logic or marking these as TODO items with a tracking issue for future implementation.

Would you like assistance in implementing these tests or should I open a GitHub issue to track this task?

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Status

Actionable comments generated: 1

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 9443f46 and 47f1633.
Files ignored due to path filters (1)
  • contracts/injective-cosmwasm-mock/Cargo.toml is excluded by: !**/*.toml
Files selected for processing (8)
  • contracts/injective-cosmwasm-mock/src/contract.rs (2 hunks)
  • contracts/injective-cosmwasm-mock/src/lib.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/msg.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/query.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/mod.rs (1 hunks)
  • packages/injective-cosmwasm/src/exchange_mock_querier.rs (5 hunks)
  • packages/injective-cosmwasm/src/querier.rs (5 hunks)
  • packages/injective-cosmwasm/src/query.rs (2 hunks)
Check Runs (1)
Lints completed (6)
Files skipped from review as they are similar to previous changes (6)
  • contracts/injective-cosmwasm-mock/src/lib.rs
  • contracts/injective-cosmwasm-mock/src/msg.rs
  • contracts/injective-cosmwasm-mock/src/query.rs
  • contracts/injective-cosmwasm-mock/src/testing/mod.rs
  • packages/injective-cosmwasm/src/exchange_mock_querier.rs
  • packages/injective-cosmwasm/src/querier.rs
Additional comments: 3
packages/injective-cosmwasm/src/query.rs (1)
  • 26-31: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [1-141]

The changes in InjectiveQuery reflect a shift towards more specific functionalities related to the Injective Protocol, such as market operations and order management. Removing Grants, GranteeGrants, and GranterGrants variants, along with DenomDecimal and DenomDecimals, and adding ExchangeParams and MarketAtomicExecutionFeeMultiplier indicate a refinement in the contract's capabilities. Ensure that these changes align with the overall design goals and that any dependent code has been updated accordingly to accommodate these changes. Additionally, consider the impact of these changes on existing integrations or clients that might rely on the removed query variants.

contracts/injective-cosmwasm-mock/src/contract.rs (2)
  • 23-25: The introduction of CREATE_SPOT_ORDER_REPLY_ID and CREATE_DERIVATIVE_ORDER_REPLY_ID constants, along with the MSG_EXEC constant, is a positive change that enhances the readability and maintainability of the code by replacing magic numbers with descriptive constants. This practice aids in understanding the code's purpose and makes future modifications easier.
  • 64-133: The extensive updates to the query function, with the addition of new query handlers such as TestExchangeParamsQuery, TestSubAccountDepositQuery, and others, significantly enhance the contract's querying capabilities. It's important to verify that these new query types are correctly integrated with the rest of the contract and that their implementations are secure and efficient. Pay particular attention to the handling of user inputs and the potential for injection attacks or other security vulnerabilities. Additionally, ensure that the responses from these queries are formatted correctly and contain all necessary information for the caller.

@jbernal87 jbernal87 force-pushed the f/testing-suite-extension branch from 47f1633 to d3b8bdf Compare March 13, 2024 11:42
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Status

Actionable comments generated: 10

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 6cf2489 and d3b8bdf.
Files ignored due to path filters (2)
  • Cargo.lock is excluded by: !**/*.lock
  • contracts/injective-cosmwasm-mock/Cargo.toml is excluded by: !**/*.toml
Files selected for processing (20)
  • .github/workflows/Basic.yml (3 hunks)
  • contracts/injective-cosmwasm-mock/src/contract.rs (2 hunks)
  • contracts/injective-cosmwasm-mock/src/error.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/handle.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/lib.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/msg.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/order_management.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/query.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/reply.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/state.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/mod.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/test_exchange.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/test_exchange_derivative.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/test_oracle.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/types.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/utils.rs (1 hunks)
  • packages/injective-cosmwasm/src/exchange/response.rs (1 hunks)
  • packages/injective-cosmwasm/src/exchange_mock_querier.rs (5 hunks)
  • packages/injective-cosmwasm/src/querier.rs (5 hunks)
  • packages/injective-cosmwasm/src/query.rs (2 hunks)
Check Runs (1)
Lints completed (6)
Files skipped from review as they are similar to previous changes (18)
  • .github/workflows/Basic.yml
  • contracts/injective-cosmwasm-mock/src/error.rs
  • contracts/injective-cosmwasm-mock/src/handle.rs
  • contracts/injective-cosmwasm-mock/src/lib.rs
  • contracts/injective-cosmwasm-mock/src/msg.rs
  • contracts/injective-cosmwasm-mock/src/order_management.rs
  • contracts/injective-cosmwasm-mock/src/query.rs
  • contracts/injective-cosmwasm-mock/src/reply.rs
  • contracts/injective-cosmwasm-mock/src/state.rs
  • contracts/injective-cosmwasm-mock/src/testing/mod.rs
  • contracts/injective-cosmwasm-mock/src/testing/test_exchange.rs
  • contracts/injective-cosmwasm-mock/src/testing/test_exchange_derivative.rs
  • contracts/injective-cosmwasm-mock/src/testing/test_oracle.rs
  • contracts/injective-cosmwasm-mock/src/types.rs
  • packages/injective-cosmwasm/src/exchange/response.rs
  • packages/injective-cosmwasm/src/exchange_mock_querier.rs
  • packages/injective-cosmwasm/src/querier.rs
  • packages/injective-cosmwasm/src/query.rs
Additional comments: 4
contracts/injective-cosmwasm-mock/src/contract.rs (3)
  • 23-25: Constants CREATE_SPOT_ORDER_REPLY_ID and CREATE_DERIVATIVE_ORDER_REPLY_ID have been added. Ensure these IDs are unique and correctly used in the reply handling logic to avoid conflicts or misrouting of replies.
  • 64-133: The query function has been expanded with new query message types. It's crucial to ensure that each query handler function (handle_*) properly sanitizes inputs and handles errors gracefully. Additionally, verify that the response structures are correctly formed and contain all necessary information.
  • 137-141: The reply function now handles replies for creating spot and derivative orders. Ensure that the reply IDs match those expected by the corresponding handlers and that error handling for unrecognized reply IDs is robust.
contracts/injective-cosmwasm-mock/src/utils.rs (1)
  • 62-159: The Setup::new function has been significantly expanded to support various testing scenarios, including spot and derivative markets. While the function is comprehensive, its complexity suggests potential for refactoring to improve readability and maintainability.

Consider breaking down this function into smaller, more focused functions to enhance code clarity.

Comment on lines 207 to 286
pub fn launch_price_feed_oracle(
app: &InjectiveTestApp,
signer: &SigningAccount,
validator: &SigningAccount,
base: &str,
quote: &str,
dec_price: String,
) {
let gov = Gov::new(app);
let oracle = Oracle::new(app);

let mut buf = vec![];
GrantPriceFeederPrivilegeProposal::encode(
&GrantPriceFeederPrivilegeProposal {
title: "test-proposal".to_string(),
description: "test-proposal".to_string(),
base: base.to_string(),
quote: quote.to_string(),
relayers: vec![signer.address()],
},
&mut buf,
)
.unwrap();

let res = gov
.submit_proposal_v1beta1(
MsgSubmitProposalV1Beta1 {
content: Some(Any {
type_url: "/injective.oracle.v1beta1.GrantPriceFeederPrivilegeProposal".to_string(),
value: buf,
}),
initial_deposit: vec![BaseCoin {
amount: "100000000000000000000".to_string(),
denom: "inj".to_string(),
}],
proposer: validator.address(),
},
validator,
)
.unwrap();

let proposal_id = res.events.iter().find(|e| e.ty == "submit_proposal").unwrap().attributes[0]
.value
.to_owned();

gov.vote(
MsgVote {
proposal_id: u64::from_str(&proposal_id).unwrap(),
voter: validator.address(),
option: 1i32,
metadata: "".to_string(),
},
validator,
)
.unwrap();

// NOTE: increase the block time in order to move past the voting period
app.increase_time(10u64);

oracle
.relay_price_feed(
MsgRelayPriceFeedPrice {
sender: signer.address(),
base: vec![base.to_string()],
quote: vec![quote.to_string()],
price: vec![dec_price], // 1.2@18dp
},
signer,
)
.unwrap();
accs.push(app.init_account(&[Coin::new(1_000_000_000_000_000_000_000_000_000, "inj")]).unwrap());
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The launch_price_feed_oracle function involves complex operations like governance proposal submission and voting. Ensure robust error handling for operations that might fail, such as proposal submission and voting, to enhance resilience.

Consider improving error handling for this function.

Comment on lines 310 to 335
pub fn launch_spot_market(exchange: &Exchange<InjectiveTestApp>, signer: &SigningAccount, ticker: String) -> String {
exchange
.instant_spot_market_launch(
MsgInstantSpotMarketLaunch {
sender: signer.address(),
ticker: ticker.clone(),
base_denom: BASE_DENOM.to_string(),
quote_denom: QUOTE_DENOM.to_string(),
min_price_tick_size: dec_to_proto(FPDecimal::must_from_str("0.000000000000001")),
min_quantity_tick_size: dec_to_proto(FPDecimal::must_from_str("1")),
},
signer,
)
.unwrap();

// Instantiate contract
let contract_address: String = wasm
.instantiate(code_id, &InstantiateMsg {}, Some(&seller.address()), Some("mock-contract"), &[], seller)
get_spot_market_id(exchange, ticker)
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The launch_spot_market and get_spot_market_id functions are crucial for setting up spot markets. While separating market launch and ID retrieval logic is good, ensure error handling is in place for .unwrap() calls to prevent panics in case of failures.

Consider adding error handling or returning a Result type.

Comment on lines 341 to 395
pub fn launch_perp_market(exchange: &Exchange<InjectiveTestApp>, signer: &SigningAccount, ticker: String) -> String {
exchange
.instant_perpetual_market_launch(
MsgInstantPerpetualMarketLaunch {
sender: signer.address(),
ticker: ticker.to_owned(),
quote_denom: "usdt".to_string(),
oracle_base: "inj".to_string(),
oracle_quote: "usdt".to_string(),
oracle_scale_factor: 6u32,
oracle_type: 2i32,
maker_fee_rate: "0".to_owned(),
taker_fee_rate: "0".to_owned(),
initial_margin_ratio: "195000000000000000".to_owned(),
maintenance_margin_ratio: "50000000000000000".to_owned(),
min_price_tick_size: "1000000000000000000000".to_owned(),
min_quantity_tick_size: "1000000000000000".to_owned(),
},
signer,
)
.unwrap();

get_perpetual_market_id(exchange, ticker)
}

pub fn get_perpetual_market_id(exchange: &Exchange<InjectiveTestApp>, ticker: String) -> String {
let perpetual_markets = exchange
.query_derivative_markets(&QueryDerivativeMarketsRequest {
status: "Active".to_string(),
market_ids: vec![],
with_mid_price_and_tob: false,
})
.unwrap()
.markets;

let market = perpetual_markets
.iter()
.filter(|m| m.market.is_some())
.find(|m| m.market.as_ref().unwrap().ticker == ticker)
.unwrap()
.market
.as_ref()
.unwrap();

market.market_id.to_string()
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similar to the spot market functions, the launch_perp_market and get_perpetual_market_id functions are essential for derivative market setup. Again, the separation of concerns is well done, but robust error handling is advised to avoid panics.

Consider improving error handling for these functions.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Status

Actionable comments generated: 7

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between d3b8bdf and 02d93c7.
Files ignored due to path filters (2)
  • Cargo.lock is excluded by: !**/*.lock
  • contracts/injective-cosmwasm-mock/Cargo.toml is excluded by: !**/*.toml
Files selected for processing (7)
  • contracts/injective-cosmwasm-mock/src/contract.rs (2 hunks)
  • contracts/injective-cosmwasm-mock/src/msg.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/query.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/mod.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/test_oracle.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/test_token_factory.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/utils.rs (1 hunks)
Files skipped from review as they are similar to previous changes (4)
  • contracts/injective-cosmwasm-mock/src/msg.rs
  • contracts/injective-cosmwasm-mock/src/query.rs
  • contracts/injective-cosmwasm-mock/src/testing/mod.rs
  • contracts/injective-cosmwasm-mock/src/testing/test_oracle.rs
Additional comments: 10
contracts/injective-cosmwasm-mock/src/testing/test_token_factory.rs (2)
  • 9-27: The test test_query_token_factory_denom_total_supply is well-structured and follows best practices for unit testing by setting up the necessary environment, executing the function under test, and asserting the expected outcome. However, consider adding a brief comment explaining the purpose of the test for future maintainability.
  • 29-37: The test test_query_token_factory_creation_fee effectively queries the token factory creation fee and asserts the expected fee. It's concise and follows good testing practices. To enhance readability and maintainability, adding a brief comment describing the test's purpose would be beneficial.
contracts/injective-cosmwasm-mock/src/contract.rs (4)
  • 24-26: The addition of CREATE_SPOT_ORDER_REPLY_ID and CREATE_DERIVATIVE_ORDER_REPLY_ID constants is a good practice for maintaining magic numbers. It enhances code readability and maintainability by providing a clear reference for reply IDs used within the contract.
  • 36-57: The implementation of TestTraderTransientSpotOrders and TestTraderTransientDerivativeOrders within the execute function introduces new functionalities for handling transient orders. Ensure comprehensive testing for these new branches, particularly focusing on financial transactions and order management. Additionally, verify that error handling within these branches provides meaningful feedback to the caller.

Would you like assistance in creating additional tests for these new functionalities?

  • 65-139: The query function has been significantly expanded to handle a wide range of new query messages. This expansion is crucial for supporting the enhanced querying capabilities of the contract. It's important to ensure that each new query handler is thoroughly tested, especially those involving financial calculations or data retrieval that could impact the contract's integrity or user experience.

Would you like assistance in creating additional tests for these new query functionalities?

  • 143-147: The reply function's handling of CREATE_SPOT_ORDER_REPLY_ID and CREATE_DERIVATIVE_ORDER_REPLY_ID through specific handlers is a structured approach to managing contract replies. This structure facilitates clear separation of concerns and enhances the contract's maintainability. Ensure that the reply handlers are well-tested, particularly in scenarios where the contract's state or user funds are affected.

Would you like assistance in creating additional tests for these reply handlers?

contracts/injective-cosmwasm-mock/src/utils.rs (4)
  • 1-35: The imports are well-organized and cover a wide range of functionalities required for the contract's operations. It's good practice to keep imports tidy and grouped by their source or functionality, which has been done here.
  • 42-48: Constants for denominations and Pyth price IDs are clearly defined and easily accessible. This is a good practice for maintainability and readability.
  • 49-63: The UserInfo and Setup structs are well-defined and encapsulate relevant data for users and test setup. It's good to see clear structuring of data for better code organization.
  • 65-69: The ExchangeType enum is a concise way to differentiate between spot, derivative, and none types. Enums are a good choice for such categorizations.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Status

Actionable comments generated: 0

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 02d93c7 and 7c455e0.
Files selected for processing (2)
  • contracts/injective-cosmwasm-mock/src/testing/test_token_factory.rs (1 hunks)
  • packages/injective-protobuf/src/proto/mod.rs (1 hunks)
Files skipped from review due to trivial changes (1)
  • packages/injective-protobuf/src/proto/mod.rs
Files skipped from review as they are similar to previous changes (1)
  • contracts/injective-cosmwasm-mock/src/testing/test_token_factory.rs

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Status

Actionable comments generated: 2

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 7c455e0 and cc26de7.
Files selected for processing (5)
  • contracts/injective-cosmwasm-mock/src/contract.rs (2 hunks)
  • contracts/injective-cosmwasm-mock/src/msg.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/query.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/mod.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/test_staking.rs (1 hunks)
Check Runs (1)
Lints failure (9)
  • contracts/injective-cosmwasm-mock/src/msg.rs: 1-1: unused import: Addr
Files skipped from review as they are similar to previous changes (1)
  • contracts/injective-cosmwasm-mock/src/testing/mod.rs
Additional comments: 3
contracts/injective-cosmwasm-mock/src/contract.rs (3)
  • 1-29: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [26-33]

The instantiate function is correctly implemented and sets the contract version as expected.

  • 64-143: The query function is correctly implemented, efficiently dispatching various QueryMsg variants to their respective handlers.
  • 146-150: The reply function is correctly implemented, handling responses from asynchronous calls and including error handling for unrecognized reply IDs.

contracts/injective-cosmwasm-mock/src/msg.rs Outdated Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Status

Actionable comments generated: 0

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between cc26de7 and 9fc60e2.
Files selected for processing (1)
  • contracts/injective-cosmwasm-mock/src/msg.rs (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • contracts/injective-cosmwasm-mock/src/msg.rs

@jbernal87 jbernal87 force-pushed the f/testing-suite-extension branch from 9fc60e2 to 6457f42 Compare March 16, 2024 09:42
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Status

Actionable comments generated: 7

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 6cf2489 and 6457f42.
Files ignored due to path filters (2)
  • Cargo.lock is excluded by: !**/*.lock
  • contracts/injective-cosmwasm-mock/Cargo.toml is excluded by: !**/*.toml
Files selected for processing (23)
  • .github/workflows/Basic.yml (3 hunks)
  • contracts/injective-cosmwasm-mock/src/contract.rs (2 hunks)
  • contracts/injective-cosmwasm-mock/src/error.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/handle.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/lib.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/msg.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/order_management.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/query.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/reply.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/state.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/mod.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/test_exchange.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/test_exchange_derivative.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/test_oracle.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/test_staking.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/test_token_factory.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/types.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/utils.rs (1 hunks)
  • packages/injective-cosmwasm/src/exchange/response.rs (1 hunks)
  • packages/injective-cosmwasm/src/exchange_mock_querier.rs (5 hunks)
  • packages/injective-cosmwasm/src/querier.rs (5 hunks)
  • packages/injective-cosmwasm/src/query.rs (2 hunks)
  • packages/injective-protobuf/src/proto/mod.rs (1 hunks)
Files skipped from review as they are similar to previous changes (21)
  • .github/workflows/Basic.yml
  • contracts/injective-cosmwasm-mock/src/error.rs
  • contracts/injective-cosmwasm-mock/src/handle.rs
  • contracts/injective-cosmwasm-mock/src/lib.rs
  • contracts/injective-cosmwasm-mock/src/msg.rs
  • contracts/injective-cosmwasm-mock/src/order_management.rs
  • contracts/injective-cosmwasm-mock/src/query.rs
  • contracts/injective-cosmwasm-mock/src/reply.rs
  • contracts/injective-cosmwasm-mock/src/state.rs
  • contracts/injective-cosmwasm-mock/src/testing/mod.rs
  • contracts/injective-cosmwasm-mock/src/testing/test_exchange.rs
  • contracts/injective-cosmwasm-mock/src/testing/test_exchange_derivative.rs
  • contracts/injective-cosmwasm-mock/src/testing/test_oracle.rs
  • contracts/injective-cosmwasm-mock/src/testing/test_staking.rs
  • contracts/injective-cosmwasm-mock/src/testing/test_token_factory.rs
  • contracts/injective-cosmwasm-mock/src/types.rs
  • packages/injective-cosmwasm/src/exchange/response.rs
  • packages/injective-cosmwasm/src/exchange_mock_querier.rs
  • packages/injective-cosmwasm/src/querier.rs
  • packages/injective-cosmwasm/src/query.rs
  • packages/injective-protobuf/src/proto/mod.rs
Additional comments: 4
contracts/injective-cosmwasm-mock/src/contract.rs (4)
  • 24-26: Constants CREATE_SPOT_ORDER_REPLY_ID and CREATE_DERIVATIVE_ORDER_REPLY_ID have been introduced to manage reply IDs for spot and derivative orders. Ensure these constants are used consistently throughout the contract to avoid magic numbers.
  • 36-57: The execute function has been updated to handle new message types for transient spot and derivative orders. Given the financial implications of these operations, it's crucial to ensure comprehensive testing, particularly focusing on financial transactions and order management. Additionally, verify that error handling within these branches provides meaningful feedback to the caller.
  • 65-142: The query function has been significantly expanded to handle a wide range of new query types. This expansion enhances the contract's querying capabilities, but it also introduces complexity. Ensure that each query handler function (handle_*) is thoroughly tested, especially for edge cases and error handling. Consider breaking down complex query handlers into smaller, more manageable functions if necessary.
  • 146-150: The reply function now handles replies for creating spot and derivative orders. Ensure that the error handling for unrecognized reply IDs is tested and that the function correctly interprets and acts upon the reply messages.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Status

Actionable comments generated: 4

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 6457f42 and 1412ab4.
Files selected for processing (7)
  • contracts/injective-cosmwasm-mock/src/contract.rs (2 hunks)
  • contracts/injective-cosmwasm-mock/src/query.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/mod.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/test_exchange.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/test_exchange_derivative.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/test_staking.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/test_wasmx.rs (1 hunks)
Files skipped from review as they are similar to previous changes (5)
  • contracts/injective-cosmwasm-mock/src/query.rs
  • contracts/injective-cosmwasm-mock/src/testing/mod.rs
  • contracts/injective-cosmwasm-mock/src/testing/test_exchange.rs
  • contracts/injective-cosmwasm-mock/src/testing/test_exchange_derivative.rs
  • contracts/injective-cosmwasm-mock/src/testing/test_staking.rs
Additional comments: 1
contracts/injective-cosmwasm-mock/src/contract.rs (1)
  • 24-26: The addition of new constants CREATE_SPOT_ORDER_REPLY_ID and CREATE_DERIVATIVE_ORDER_REPLY_ID is clear and follows best practices for defining magic numbers. Ensure these constants are used consistently throughout the contract for reply handling.

Comment on lines +6 to +18
#[test]
#[cfg_attr(not(feature = "integration"), ignore)]
fn test_query_contract_registration_info() {
let env = Setup::new(ExchangeType::None);
let wasm = Wasm::new(&env.app);

let query_msg = QueryMsg::TestQueryContractRegistrationInfo {
contract_address: env.contract_address.to_owned(),
};

let response: QueryContractRegistrationInfoResponse = wasm.query(&env.contract_address, &query_msg).unwrap();
assert!(response.contract.is_none())
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test function test_query_contract_registration_info is well-structured and follows good testing practices by setting up the necessary environment, executing the query, and asserting the expected outcome. However, it's important to ensure that the test covers various scenarios, including potential error cases and different contract states. Consider adding more test cases to cover these aspects comprehensively.

Would you like me to help generate additional test cases to cover various scenarios?

Comment on lines +65 to +141
QueryMsg::TestExchangeParamsQuery {} => handle_exchange_params_query(&querier),
QueryMsg::TestSubAccountDepositQuery { subaccount_id, denom } => handle_subaccount_deposit_query(&querier, &subaccount_id, denom),
QueryMsg::TestSpotMarketQuery { market_id } => handle_spot_market_query(&querier, &market_id),
QueryMsg::TestDerivativeMarketQuery { market_id } => handle_derivative_market_query(&querier, &market_id),
QueryMsg::TestEffectiveSubaccountPosition { market_id, subaccount_id } => {
handle_effective_subaccount_position_query(&querier, &market_id, &subaccount_id)
}
QueryMsg::TestVanillaSubaccountPosition { market_id, subaccount_id } => {
handle_vanilla_subaccount_position_query(&querier, &market_id, &subaccount_id)
}
QueryMsg::TestTraderDerivativeOrders { market_id, subaccount_id } => {
handle_trader_derivative_orders_query(&querier, &market_id, &subaccount_id)
}
QueryMsg::TestTraderSpotOrders { market_id, subaccount_id } => handle_trader_spot_orders_query(&querier, &market_id, &subaccount_id),
QueryMsg::TestSpotOrdersToCancelUpToAmount {
market_id,
subaccount_id,
base_amount,
quote_amount,
strategy,
reference_price,
} => handle_spot_orders_to_cancel_up_to_amount_query(
&querier,
&market_id,
&subaccount_id,
base_amount,
quote_amount,
strategy,
reference_price,
),
QueryMsg::TestDerivativeOrdersToCancelUpToAmount {
market_id,
subaccount_id,
quote_amount,
strategy,
reference_price,
} => handle_derivative_orders_to_cancel_up_to_amount_query(&querier, &market_id, &subaccount_id, quote_amount, strategy, reference_price),
QueryMsg::TestPerpetualMarketInfo { market_id } => handle_perpetual_market_info_query(&querier, &market_id),
QueryMsg::TestPerpetualMarketFunding { market_id } => handle_perpetual_market_funding_query(&querier, &market_id),
QueryMsg::TestMarketVolatility {
market_id,
trade_grouping_sec,
max_age,
include_raw_history,
include_metadata,
} => handle_market_volatility_query(&querier, &market_id, trade_grouping_sec, max_age, include_raw_history, include_metadata),
QueryMsg::TestDerivativeMarketMidPriceAndTob { market_id } => handle_derivative_market_mid_price_and_tob_query(&querier, &market_id),
QueryMsg::TestAggregateMarketVolume { market_id } => handle_aggregate_market_volume_query(&querier, &market_id),
QueryMsg::TestAggregateAccountVolume { account_id } => handle_aggregate_account_volume_query(&querier, account_id),
QueryMsg::TestSpotMarketMidPriceAndTob { market_id } => handle_spot_market_mid_price_and_tob_query(&querier, &market_id),
QueryMsg::TestSpotMarketOrderbook {
market_id,
side,
limit_cumulative_quantity,
limit_cumulative_notional,
} => handle_spot_market_orderbook_query(&querier, &market_id, side, limit_cumulative_quantity, limit_cumulative_notional),
QueryMsg::TestDerivativeMarketOrderbook {
market_id,
limit_cumulative_notional,
} => handle_derivative_market_orderbook_query(&querier, &market_id, limit_cumulative_notional),
QueryMsg::TestMarketAtomicExecutionFeeMultiplier { market_id } => handle_market_atomic_execution_fee_multiplier_query(&querier, &market_id),
QueryMsg::TestQueryOracleVolatility {
base_info,
quote_info,
max_age,
include_raw_history,
include_metadata,
} => handle_oracle_volatility_query(&querier, base_info, quote_info, max_age, include_raw_history, include_metadata),
QueryMsg::TestQueryOraclePrice { oracle_type, base, quote } => handle_oracle_price_query(&querier, &oracle_type, base, quote),
QueryMsg::TestQueryPythPrice { price_id } => handle_pyth_price_query(&querier, price_id),
QueryMsg::TestQueryStakedAmount {
delegator_address,
max_delegations,
} => handle_staked_amount_query(&querier, deps.api.addr_validate(delegator_address.as_str())?, max_delegations),
QueryMsg::TestQueryTokenFactoryDenomTotalSupply { denom } => handle_token_factory_denom_total_supply(&querier, denom),
QueryMsg::TestQueryTokenFactoryCreationFee {} => handle_token_factory_creation_fee(&querier),
QueryMsg::TestQueryContractRegistrationInfo { contract_address } => handle_contract_registration_info_query(&querier, contract_address),
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The query handling function has been significantly expanded to cover a wide range of new queries. This expansion is crucial for supporting the contract's enhanced trading functionalities. Ensure that each query handler is thoroughly tested, especially for edge cases and error handling scenarios. It's also important to maintain consistency in how queries are processed and ensure that the contract's state is correctly managed across queries.

Would you like me to help generate additional test cases for these new query handlers?

Comment on lines +146 to +150
pub fn reply(deps: DepsMut<InjectiveQueryWrapper>, _env: Env, msg: Reply) -> Result<Response, ContractError> {
match msg.id {
CREATE_SPOT_ORDER_REPLY_ID => handle_create_order_reply(deps, &msg),
CREATE_DERIVATIVE_ORDER_REPLY_ID => handle_create_derivative_order_reply(deps, &msg),
_ => Err(ContractError::UnrecognizedReply(msg.id)),
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reply handling function has been updated to handle replies for creating spot and derivative orders. This is a critical part of the contract's interaction with the Injective Protocol. Ensure that the reply handling is robust, correctly interprets the replies, and updates the contract's state as necessary. Consider adding more comprehensive tests to cover various reply scenarios and error cases.

Would you like assistance in creating additional tests for reply handling?

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Status

Actionable comments generated: 1

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 1412ab4 and fdf3a9f.
Files selected for processing (1)
  • CHANGELOG.md (1 hunks)
Additional comments: 2
CHANGELOG.md (2)
  • 20-21: The description of the fix for the exchange aggregate volume query is clear and concise.
  • 23-25: The items listed under the Removed section are clearly stated.

CHANGELOG.md Outdated Show resolved Hide resolved
…n factory, wasmx and staking tests. add changelog
@jbernal87 jbernal87 force-pushed the f/testing-suite-extension branch from fdf3a9f to e921edc Compare March 18, 2024 12:01
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Status

Actionable comments generated: 8

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 6cf2489 and e921edc.
Files ignored due to path filters (2)
  • Cargo.lock is excluded by: !**/*.lock
  • contracts/injective-cosmwasm-mock/Cargo.toml is excluded by: !**/*.toml
Files selected for processing (25)
  • .github/workflows/Basic.yml (3 hunks)
  • CHANGELOG.md (1 hunks)
  • contracts/injective-cosmwasm-mock/src/contract.rs (2 hunks)
  • contracts/injective-cosmwasm-mock/src/error.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/handle.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/lib.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/msg.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/order_management.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/query.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/reply.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/state.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/mod.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/test_exchange.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/test_exchange_derivative.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/test_oracle.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/test_staking.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/test_token_factory.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/testing/test_wasmx.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/types.rs (1 hunks)
  • contracts/injective-cosmwasm-mock/src/utils.rs (1 hunks)
  • packages/injective-cosmwasm/src/exchange/response.rs (1 hunks)
  • packages/injective-cosmwasm/src/exchange_mock_querier.rs (5 hunks)
  • packages/injective-cosmwasm/src/querier.rs (5 hunks)
  • packages/injective-cosmwasm/src/query.rs (2 hunks)
  • packages/injective-protobuf/src/proto/mod.rs (1 hunks)
Files skipped from review as they are similar to previous changes (22)
  • .github/workflows/Basic.yml
  • contracts/injective-cosmwasm-mock/src/error.rs
  • contracts/injective-cosmwasm-mock/src/handle.rs
  • contracts/injective-cosmwasm-mock/src/lib.rs
  • contracts/injective-cosmwasm-mock/src/msg.rs
  • contracts/injective-cosmwasm-mock/src/order_management.rs
  • contracts/injective-cosmwasm-mock/src/query.rs
  • contracts/injective-cosmwasm-mock/src/reply.rs
  • contracts/injective-cosmwasm-mock/src/state.rs
  • contracts/injective-cosmwasm-mock/src/testing/mod.rs
  • contracts/injective-cosmwasm-mock/src/testing/test_exchange.rs
  • contracts/injective-cosmwasm-mock/src/testing/test_exchange_derivative.rs
  • contracts/injective-cosmwasm-mock/src/testing/test_oracle.rs
  • contracts/injective-cosmwasm-mock/src/testing/test_staking.rs
  • contracts/injective-cosmwasm-mock/src/testing/test_token_factory.rs
  • contracts/injective-cosmwasm-mock/src/testing/test_wasmx.rs
  • contracts/injective-cosmwasm-mock/src/types.rs
  • packages/injective-cosmwasm/src/exchange/response.rs
  • packages/injective-cosmwasm/src/exchange_mock_querier.rs
  • packages/injective-cosmwasm/src/querier.rs
  • packages/injective-cosmwasm/src/query.rs
  • packages/injective-protobuf/src/proto/mod.rs
Additional comments: 6
contracts/injective-cosmwasm-mock/src/contract.rs (3)
  • 36-57: The execute function has been expanded to include handling for transient spot and derivative orders. This is a significant enhancement to the contract's functionality. Ensure comprehensive testing for these new branches, particularly focusing on financial transactions and order management. Additionally, verify that error handling within these branches provides meaningful feedback to the caller.

Would you like assistance in creating additional tests for these new functionalities?

  • 65-141: The query handling function has been significantly expanded to cover a wide range of new queries. This expansion is crucial for supporting the contract's enhanced trading functionalities. Ensure that each query handler is thoroughly tested, especially for edge cases and error handling scenarios. It's also important to maintain consistency in how queries are processed and ensure that the contract's state is correctly managed across queries.

Would you like me to help generate additional test cases for these new query handlers?

  • 146-150: The reply handling function has been updated to handle replies for creating spot and derivative orders. This is a critical part of the contract's interaction with the Injective Protocol. Ensure that the reply handling is robust, correctly interprets the replies, and updates the contract's state as necessary. Consider adding more comprehensive tests to cover various reply scenarios and error cases.

Would you like assistance in creating additional tests for reply handling?

contracts/injective-cosmwasm-mock/src/utils.rs (3)
  • 1-34: The imports and constants defined at the beginning of the file are well-organized and provide a clear overview of the dependencies and constants used throughout the utility functions. This organization aids in maintainability and readability.
  • 49-63: The UserInfo and Setup structures are well-defined and encapsulate relevant data for user information and test setup, respectively. However, consider adding documentation comments to explain the purpose and usage of these structures, especially for complex fields like denoms and market_id in Setup, to improve code readability and maintainability.
  • 65-69: The ExchangeType enum is a good use of Rust's type system to clearly differentiate between spot, derivative, and none exchange types. This enhances code clarity and type safety.

Comment on lines +201 to +214
pub fn send(bank: &Bank<InjectiveTestApp>, amount: &str, denom: &str, from: &SigningAccount, to: &SigningAccount) {
bank.send(
MsgSend {
from_address: from.address(),
to_address: to.address(),
amount: vec![BaseCoin {
amount: amount.to_string(),
denom: denom.to_string(),
}],
},
from,
)
.unwrap();
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The use of .unwrap() in the send function could lead to panics in case of errors. It's advisable to handle errors more gracefully or return a Result type to improve robustness and error resilience. This feedback aligns with the previous review, and the suggested change remains relevant.

- .unwrap();
+ ?;

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
pub fn send(bank: &Bank<InjectiveTestApp>, amount: &str, denom: &str, from: &SigningAccount, to: &SigningAccount) {
bank.send(
MsgSend {
from_address: from.address(),
to_address: to.address(),
amount: vec![BaseCoin {
amount: amount.to_string(),
denom: denom.to_string(),
}],
},
from,
)
.unwrap();
}
pub fn send(bank: &Bank<InjectiveTestApp>, amount: &str, denom: &str, from: &SigningAccount, to: &SigningAccount) {
bank.send(
MsgSend {
from_address: from.address(),
to_address: to.address(),
amount: vec![BaseCoin {
amount: amount.to_string(),
denom: denom.to_string(),
}],
},
from,
)
?;
}

Comment on lines +397 to +424
#[derive(Clone)]
pub struct HumanOrder {
pub price: String,
pub quantity: String,
pub order_type: OrderType,
}
pub fn add_spot_order_as(app: &InjectiveTestApp, market_id: String, trader: &UserInfo, price: String, quantity: String, order_type: OrderType) {
let exchange = Exchange::new(app);
exchange
.create_spot_limit_order(
MsgCreateSpotLimitOrder {
sender: trader.account.address().clone(),
order: Some(SpotOrder {
market_id: market_id.to_owned(),
order_info: Some(OrderInfo {
subaccount_id: trader.subaccount_id.to_string(),
fee_recipient: trader.account.address(),
price,
quantity,
}),
order_type: order_type.into(),
trigger_price: "".to_string(),
}),
},
&trader.account,
)
.unwrap();
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The add_spot_order_as function uses .unwrap() for handling the response, which could lead to panics. Handling errors gracefully or returning a Result to the caller is advisable to improve robustness. This feedback aligns with the previous review, and the suggested change remains relevant.

Consider revising error handling to improve robustness.

Comment on lines +518 to +549
pub fn add_derivative_order_as(
app: &InjectiveTestApp,
market_id: String,
trader: &SigningAccount,
price: String,
quantity: String,
order_type: OrderType,
margin: String,
) {
let exchange = Exchange::new(app);
exchange
.create_derivative_limit_order(
MsgCreateDerivativeLimitOrder {
sender: trader.address(),
order: Some(DerivativeOrder {
market_id: market_id.to_owned(),
order_info: Some(OrderInfo {
subaccount_id: get_default_subaccount_id_for_checked_address(&Addr::unchecked(trader.address()))
.as_str()
.to_string(),
fee_recipient: trader.address(),
price,
quantity,
}),
margin,
order_type: order_type.into(),
trigger_price: "".to_string(),
}),
},
trader,
)
.unwrap();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similar to add_spot_order_as, the add_derivative_order_as function also uses .unwrap(). Enhancing error handling would make the function more resilient to failures. This feedback aligns with the previous review, and the suggested change remains relevant.

Consider revising error handling to improve robustness.

Comment on lines +573 to +587
pub fn revoke_authorization(app: &InjectiveTestApp, granter: &SigningAccount, grantee: String, msg_type_url: String) {
let _res: ExecuteResponse<MsgRevokeResponse> = app
.execute_multiple(
&[(
MsgRevoke {
granter: granter.address(),
grantee,
msg_type_url,
},
MsgRevoke::TYPE_URL,
)],
granter,
)
.unwrap();
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The revoke_authorization function demonstrates how to revoke an authorization but uses .unwrap() which could lead to runtime panics. It's important to handle potential errors to avoid such issues. This feedback aligns with the previous review, and the suggested change remains relevant.

Consider adding error handling or returning a Result type.

Comment on lines +589 to +611
pub fn create_generic_authorization(app: &InjectiveTestApp, granter: &SigningAccount, grantee: String, msg: String, expiration: Option<Timestamp>) {
let authz = Authz::new(app);

let mut buf = vec![];
GenericAuthorization::encode(&GenericAuthorization { msg }, &mut buf).unwrap();

authz
.grant(
MsgGrant {
granter: granter.address(),
grantee,
grant: Some(Grant {
authorization: Some(Any {
type_url: "/cosmos.authz.v1beta1.GenericAuthorization".to_string(),
value: buf.clone(),
}),
expiration,
}),
},
granter,
)
.unwrap();
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The create_generic_authorization function uses .unwrap() which could lead to panics. Improving error handling would enhance the function's reliability. This feedback aligns with the previous review, and the suggested change remains relevant.

Consider revising error handling to improve robustness.

CHANGELOG.md Outdated
Comment on lines 8 to 25
## [Unreleased] - yyyy-mm-dd

### Added

### Changed


## [Unreleased] - 2024-03-18

### Added
- Tests queries (injective-cosmwasm-mock) covering functionality of querier.rs

### Fixed
- Exchange aggregate volume query to use the correct parsing.

### Removed
- Grants related queries.
- Exchange denom decimal query.
Copy link

@coderabbitai coderabbitai bot Mar 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The "Unreleased" section appears twice with different dates (yyyy-mm-dd and 2024-03-18). It seems like a duplication error. Consider merging these sections under a single "Unreleased" header to maintain clarity and avoid confusion about the changes made.

-## [Unreleased] - yyyy-mm-dd
-### Added
-### Changed
-
 ## [Unreleased] - 2024-03-18

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
## [Unreleased] - yyyy-mm-dd
### Added
### Changed
## [Unreleased] - 2024-03-18
### Added
- Tests queries (injective-cosmwasm-mock) covering functionality of querier.rs
### Fixed
- Exchange aggregate volume query to use the correct parsing.
### Removed
- Grants related queries.
- Exchange denom decimal query.
## [Unreleased] - 2024-03-18
### Added
- Tests queries (injective-cosmwasm-mock) covering functionality of querier.rs
### Fixed
- Exchange aggregate volume query to use the correct parsing.
### Removed
- Grants related queries.
- Exchange denom decimal query.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

@jbernal87 jbernal87 requested a review from maxrobot March 18, 2024 15:18
Copy link
Contributor

@maxrobot maxrobot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall this looks like good work to me, I think we should do the following:

  1. remove any queries that DO NOT WORK
  2. create and publish new version of cw-injective
  3. Discuss the next steps with @gorgos

CHANGELOG.md Outdated
Comment on lines 8 to 25
## [Unreleased] - yyyy-mm-dd

### Added

### Changed


## [Unreleased] - 2024-03-18

### Added
- Tests queries (injective-cosmwasm-mock) covering functionality of querier.rs

### Fixed
- Exchange aggregate volume query to use the correct parsing.

### Removed
- Grants related queries.
- Exchange denom decimal query.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Status

Actionable comments generated: 0

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between e921edc and b8cad52.
Files ignored due to path filters (1)
  • Cargo.lock is excluded by: !**/*.lock
Files selected for processing (2)
  • packages/injective-cosmwasm/CHANGELOG.md (1 hunks)
  • packages/injective-cosmwasm/src/exchange_mock_querier.rs (5 hunks)
Files skipped from review as they are similar to previous changes (1)
  • packages/injective-cosmwasm/src/exchange_mock_querier.rs
Additional comments: 2
packages/injective-cosmwasm/CHANGELOG.md (2)
  • 18-18: Consider providing more specific details about the aspects of querier.rs functionality that the new tests cover. This will help users understand the scope of the tests better.
  • 23-25: It would be helpful to include brief reasons for the removal of features (grants related queries and exchange denom decimal query) in the changelog. This can offer clarity to the users about the changes and the direction of the project.

@jbernal87 jbernal87 requested a review from gorgos March 21, 2024 14:35
Copy link
Member

@gorgos gorgos left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, just one question

Comment on lines -29 to -43
// Authz
Grants {
granter: String,
grantee: String,
msg_type_url: String,
pagination: Option<u32>,
},
GranteeGrants {
grantee: String,
pagination: Option<u32>,
},
GranterGrants {
granter: String,
pagination: Option<u32>,
},
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These queries didn't work or why are they removed?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

They where removed because they didn't work

@jbernal87 jbernal87 merged commit 944c0f7 into dev Mar 22, 2024
4 checks passed
@jbernal87 jbernal87 deleted the f/testing-suite-extension branch March 22, 2024 21:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants